package main

import (
	"fmt"
	"html/template"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
)

var (
	server *http.Server
	restartChan = make(chan struct{}, 1)
)

func restartServerLoop() {
	for range restartChan {
		log.Println("Restarting web server via channel...")
		startServer()
	}
}

func startServer() {
	if server != nil {
		log.Println("Shutting down old server on port", server.Addr)
		if err := server.Close(); err != nil {
			log.Printf("Error closing old server: %v", err)
		} else {
			log.Println("Old server closed successfully.")
		}
	}

	mux := http.NewServeMux()

	mux.Handle("/uploads/", http.StripPrefix("/uploads/", http.FileServer(http.Dir(filepath.Join("assets", "uploads")))))
	mux.Handle("/files/", http.StripPrefix("/files/", http.FileServer(http.Dir("files"))))

	mux.HandleFunc("/output.txt", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "output.txt")
	})
	mux.HandleFunc("/output.m3u", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "output.m3u")
	})

	mux.HandleFunc("/upload-file", uploadFileHandler)

	mux.HandleFunc("/", homeHandler)
	mux.HandleFunc("/save", saveHandler)
	mux.HandleFunc("/get-movies", getMoviesHandler)
	mux.HandleFunc("/delete-movie", deleteMovieHandler)
	mux.HandleFunc("/edit-movie", editMovieHandler)
	mux.HandleFunc("/copy-txt", copyTxtHandler)
	mux.HandleFunc("/copy-m3u", copyM3uHandler)
	mux.HandleFunc("/export-data", exportDataHandler)
	mux.HandleFunc("/import-data", importDataHandler)
	mux.HandleFunc("/set-port", setPortHandler)
	mux.HandleFunc("/restart-server", restartServerHandler)

	port := getCurrentPort()
	addr := ":" + port
	newServer := &http.Server{Addr: addr, Handler: mux}

	server = newServer

	log.Println("Starting new HTTP server on", addr)
	go func() {
		if err := server.ListenAndServe(); err != http.ErrServerClosed {
			log.Printf("HTTP server error on %s: %v", addr, err)
		} else {
			log.Printf("HTTP server on %s closed gracefully", addr)
		}
	}()
}

func restartServerHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}
	select {
	case restartChan <- struct{}{}:
		w.WriteHeader(http.StatusOK)
		fmt.Fprint(w, "Server restart initiated")
	default:
		log.Println("Restart request ignored, restart already queued or in progress")
		w.WriteHeader(http.StatusOK)
		fmt.Fprint(w, "Server restart already queued or in progress")
	}
}

func uploadFileHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	err := r.ParseMultipartForm(32 << 20)
	if err != nil {
		http.Error(w, "Failed to parse form", http.StatusBadRequest)
		return
	}

	file, handler, err := r.FormFile("file")
	if err != nil {
		http.Error(w, "Failed to get file", http.StatusBadRequest)
		return
	}
	defer file.Close()

	if handler.Filename == "" {
		http.Error(w, "Filename is required", http.StatusBadRequest)
		return
	}

	uploadDir := "files"
	filePath := filepath.Join(uploadDir, filepath.Base(handler.Filename))

	if err := os.MkdirAll(uploadDir, 0755); err != nil {
		log.Printf("Error creating upload directory: %v", err)
		http.Error(w, "Failed to create upload directory", http.StatusInternalServerError)
		return
	}

	dst, err := os.Create(filePath)
	if err != nil {
		log.Printf("Error creating file: %v", err)
		http.Error(w, "Failed to save file", http.StatusInternalServerError)
		return
	}
	defer dst.Close()

	_, err = dst.ReadFrom(file)
	if err != nil {
		log.Printf("Error copying file: %v", err)
		http.Error(w, "Failed to save file", http.StatusInternalServerError)
		return
	}

	log.Printf("File uploaded successfully: %s", filePath)
	w.WriteHeader(http.StatusOK)
	fmt.Fprint(w, "File uploaded successfully")
}

func setPortHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}
	port := r.FormValue("port")
	if port == "" {
		http.Error(w, "Port is required", http.StatusBadRequest)
		return
	}
	if portNum, err := strconv.Atoi(port); err != nil || portNum < 1 || portNum > 65535 {
		http.Error(w, "Invalid port number", http.StatusBadRequest)
		return
	}
	setPort(port)
	w.WriteHeader(http.StatusOK)
	fmt.Fprint(w, "Port saved successfully")
}

var homeTemplate = template.Must(template.New("").Parse(`<!DOCTYPE html>
<html>
<head>
    <title>Movie Tool</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .container {
            display: flex;
            max-width: 1920px;
            height: calc(100vh - 40px);
            margin: 0 auto;
            background-color: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .left-panel {
            flex: 1;
            padding: 30px;
            border-right: 1px solid #e1e8ed;
            background: #f8f9fa;
            display: flex;
            flex-direction: column;
            overflow-y: auto;
        }
        .right-panel {
            flex: 2;
            padding: 30px;
            display: flex;
            flex-direction: column;
            background: #ffffff;
        }
        h1 {
            color: #2c3e50;
            text-align: center;
            margin-bottom: 25px;
            font-size: 24px;
            font-weight: 600;
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #34495e;
            font-size: 14px;
        }
        input[type="text"], input[type="file"], select {
            width: 100%;
            padding: 12px;
            border: 2px solid #e1e8ed;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s ease;
        }
        input[type="text"]:focus, select:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
        }
        button {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 12px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }
        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        .btn-group {
            display: flex;
            gap: 12px;
            margin-top: 20px;
        }
        .btn-group button {
            flex: 1;
        }
        .address-display {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            padding: 12px;
            border-radius: 8px;
            margin: 12px 0;
            word-break: break-all;
            font-family: monospace;
            font-size: 13px;
            border: 1px solid #e1e8ed;
        }
        .copy-btn {
            background: linear-gradient(135deg, #2ecc71 0%, #27ae60 100%);
            padding: 6px 12px;
            font-size: 12px;
            margin-left: 8px;
            border-radius: 6px;
        }
        .copy-btn:hover {
            transform: none;
            box-shadow: 0 3px 10px rgba(0,0,0,0.15);
        }
        .delete-btn, .edit-btn, .play-btn, .import-btn, .export-btn, .search-btn {
            padding: 6px 12px;
            font-size: 12px;
            margin-left: 5px;
            border-radius: 6px;
            font-weight: 500;
        }
        .delete-btn {
            background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
        }
        .edit-btn {
            background: linear-gradient(135deg, #f39c12 0%, #d35400 100%);
            color: white;
        }
        .play-btn {
            background: linear-gradient(135deg, #2ecc71 0%, #27ae60 100%);
        }
        .import-btn {
            background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
        }
        .export-btn {
            background: linear-gradient(135deg, #9b59b6 0%, #8e44ad 100%);
        }
        .search-btn {
            background: linear-gradient(135deg, #95a5a6 0%, #7f8c8d 100%);
        }
        .movies-list {
            margin-top: 20px;
            flex: 1;
            overflow-y: auto;
            max-height: calc(100vh - 250px);
            border: 2px solid #e1e8ed;
            border-radius: 10px;
            padding: 15px;
            background: #fafafa;
        }
        .movie-item {
            display: flex;
            align-items: center;
            padding: 15px;
            border: 1px solid #e1e8ed;
            margin-bottom: 12px;
            border-radius: 10px;
            background: white;
            transition: transform 0.2s ease, box-shadow 0.2s ease;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .movie-item:hover {
            transform: translateX(5px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
        }
        .movie-item.highlighted {
            background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%);
            border-color: #ffc107;
        }
        .movie-item img {
            width: 60px;
            height: 60px;
            object-fit: cover;
            margin-right: 15px;
            border-radius: 8px;
            border: 2px solid #e1e8ed;
        }
        .movie-info {
            flex: 1;
        }
        .movie-name {
            font-weight: 600;
            color: #2c3e50;
            font-size: 16px;
            margin-bottom: 5px;
        }
        .movie-url {
            font-size: 12px;
            color: #7f8c8d;
            word-break: break-all;
        }
        .movie-actions {
            display: flex;
            gap: 5px;
        }
        .image-input-group {
            border: 2px dashed #3498db;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            margin-bottom: 15px;
            background: rgba(52, 152, 219, 0.05);
        }
        .image-input-group label {
            display: block;
            margin-bottom: 12px;
            color: #34495e;
            font-weight: 600;
            font-size: 14px;
        }
        .image-input-group input {
            margin: 8px 0;
        }
        .editing {
            background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%);
            border: 2px solid #ffc107;
        }
        .editing label {
            color: #856404;
        }
        .search-container {
            display: flex;
            margin-bottom: 15px;
        }
        .search-container input {
            flex: 1;
            margin-right: 8px;
        }
        .ads-container {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 20px;
            border-radius: 12px;
            margin-top: 20px;
            text-align: center;
            color: white;
        }
        .ads-container h3 {
            margin-bottom: 12px;
            font-size: 16px;
            font-weight: 600;
        }
        .ads-container p {
            margin: 8px 0;
            font-size: 14px;
        }
        .ads-container a {
            color: #fff;
            text-decoration: none;
            font-weight: 600;
            border-bottom: 1px solid rgba(255,255,255,0.5);
        }
        .ads-container a:hover {
            border-bottom-color: white;
        }
        .http-service-section {
            background: linear-gradient(135deg, #1abc9c 0%, #16a085 100%);
            padding: 20px;
            border-radius: 12px;
            margin-top: 20px;
            color: white;
        }
        .http-service-section h3 {
            margin-bottom: 12px;
            font-size: 16px;
            font-weight: 600;
        }
        .http-service-section p {
            margin: 8px 0;
            font-size: 14px;
            opacity: 0.9;
        }
        .http-service-section a {
            color: #fff;
            text-decoration: none;
            font-weight: 600;
            border-bottom: 1px solid rgba(255,255,255,0.5);
        }
        .http-service-section a:hover {
            border-bottom-color: white;
        }
        .upload-section {
            background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
            padding: 20px;
            border-radius: 12px;
            margin-top: 20px;
            color: white;
        }
        .upload-section h3 {
            margin-bottom: 12px;
            font-size: 16px;
            font-weight: 600;
        }
        .upload-section .form-group {
            margin-bottom: 15px;
        }
        .upload-section .form-group input[type="file"] {
            background-color: white;
            color: #2c3e50;
            border: 1px solid #2980b9;
        }
        .upload-section button {
            background: linear-gradient(135deg, #2ecc71 0%, #27ae60 100%);
            width: 100%;
            padding: 10px;
        }
        .upload-section button:hover {
            transform: none;
            box-shadow: 0 3px 10px rgba(0,0,0,0.15);
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="left-panel">
            <h1>🎬 电影管理工具</h1>
            
            <form id="movieForm" enctype="multipart/form-data">
                <input type="hidden" id="editId" name="id">
                <div class="form-group">
                    <label for="name">电影名称:</label>
                    <input type="text" id="name" name="name" required placeholder="请输入电影名称">
                </div>

                <div class="form-group">
                    <label for="url">URL:</label>
                    <input type="text" id="url" name="url" required placeholder="请输入直播流地址">
                </div>

                <div class="form-group">
                    <div class="image-input-group">
                        <label>封面图片 (本地文件或网络 URL):</label>
                        <input type="file" id="imageFile" name="imageFile" accept="image/*">
                        <input type="text" id="imageUrl" name="imageUrl" placeholder="或输入网络图片 URL">
                    </div>
                </div>

                <div class="btn-group">
                    <button type="submit" id="saveBtn">💾 保存电影</button>
                    <button type="button" onclick="cancelEdit()">❌ 取消编辑</button>
                </div>
            </form>

            <div class="btn-group" style="margin-top: 20px;">
                <button class="import-btn" onclick="importData()">📥 导入数据</button>
                <button class="export-btn" onclick="exportData()">📤 导出数据</button>
            </div>

            <div class="http-service-section">
                <h3>🌐 HTTP 文件服务</h3>
                <p>访问地址: <span id="filesAddress">加载中...</span></p>
                <p>将文件放入 <strong>files</strong> 文件夹即可访问</p>
            </div>

            <div class="upload-section">
                <h3>⬆️ 局域网文件上传</h3>
                <div class="form-group">
                    <label for="uploadFile">选择文件:</label>
                    <input type="file" id="uploadFile" name="file" required>
                </div>
                <button id="uploadBtn" onclick="uploadFile()">📤 上传到 files 文件夹</button>
            </div>

            <div class="ads-container">
                <h3>🌟 关注作者</h3>
                <p>🎮 B站: <a href="https://space.bilibili.com/259653117  " target="_blank">冰之河1314</a></p>
                <p>📱 抖音: <a href="https://www.douyin.com/search/938527487  " target="_blank">冰之河</a></p>
            </div>

            <div style="margin-top: 25px;">
                <h3>🔗 网络地址</h3>
                <div class="address-display">
                    <strong>TXT 地址:</strong> <span id="txtAddress">加载中...</span>
                    <button class="copy-btn" onclick="copyToClipboard('txtAddress')">📋 复制</button>
                </div>
                <div class="address-display">
                    <strong>M3U 地址:</strong> <span id="m3uAddress">加载中...</span>
                    <button class="copy-btn" onclick="copyToClipboard('m3uAddress')">📋 复制</button>
                </div>
            </div>
        </div>

        <div class="right-panel">
            <h1>📚 已添加的电影</h1>
            
            <div class="search-container">
                <input type="text" id="searchInput" placeholder="🔍 搜索电影名称或URL...">
                <button class="search-btn" onclick="searchMovies()">🔍 搜索</button>
            </div>
            
            <div id="moviesContainer" class="movies-list">
            </div>
        </div>
    </div>

    <script>
        let isEditing = false;
        let currentMovie = null;
        let allMovies = [];

        async function loadIPAddresses() {
            try {
                const response = await fetch('/copy-txt');
                if (!response.ok) {
                    throw new Error('HTTP error! status: ' + response.status);
                }
                const fullAddress = await response.text();
                const urlObj = new URL(fullAddress);
                const ip = urlObj.hostname;
                const port = urlObj.port;

                const filesAddress = 'http://' + ip + ':' + port + '/files/';
                document.getElementById('filesAddress').textContent = filesAddress;
                document.getElementById('filesAddress').innerHTML = '<a href="' + filesAddress + '" target="_blank">' + filesAddress + '</a>';
                document.getElementById('txtAddress').textContent = 'http://' + ip + ':' + port + '/output.txt';
                document.getElementById('m3uAddress').textContent = 'http://' + ip + ':' + port + '/output.m3u';

            } catch (error) {
                console.error('Failed to load IP addresses:', error);
                const host = window.location.host;
                const filesAddress = 'http://' + host + '/files/';
                document.getElementById('filesAddress').innerHTML = '<a href="' + filesAddress + '" target="_blank">' + filesAddress + '</a>';
                document.getElementById('txtAddress').textContent = 'http://' + host + '/output.txt';
                document.getElementById('m3uAddress').textContent = 'http://' + host + '/output.m3u';
            }
        }

        document.getElementById('movieForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            const formData = new FormData(e.target);
            
            const name = document.getElementById('name').value;
            const url = document.getElementById('url').value;
            
            if (checkDuplicate(name, url)) {
                alert('⚠️ 已存在相同名称或URL的电影！');
                return;
            }
            
            const urlPath = isEditing ? '/edit-movie' : '/save';
            const response = await fetch(urlPath, {
                method: 'POST',
                body: formData
            });
            
            if (response.ok) {
                alert(isEditing ? '✅ 修改成功！' : '✅ 保存成功！');
                e.target.reset();
                isEditing = false;
                currentMovie = null;
                document.getElementById('movieForm').classList.remove('editing');
                document.getElementById('saveBtn').textContent = '💾 保存电影';
                loadMovies();
                loadAddresses();
            } else {
                alert(isEditing ? '❌ 修改失败！' : '❌ 保存失败！');
            }
        });

        function checkDuplicate(name, url) {
            if (!Array.isArray(allMovies)) {
                console.warn('allMovies is not an array, cannot check duplicate.');
                return false;
            }

            const currentEditId = parseInt(document.getElementById('editId').value);

            return allMovies.some(movie => {
                if (isEditing && movie.id === currentEditId) {
                    return false;
                }
                return movie.name === name || movie.url === url;
            });
        }

        function cancelEdit() {
            document.getElementById('movieForm').reset();
            isEditing = false;
            currentMovie = null;
            document.getElementById('movieForm').classList.remove('editing');
            document.getElementById('saveBtn').textContent = '💾 保存电影';
        }

        async function loadAddresses() {
            try {
                const response = await fetch('/copy-txt');
                if (!response.ok) {
                    throw new Error('HTTP error! status: ' + response.status);
                }
                const fullAddress = await response.text();
                const urlObj = new URL(fullAddress);
                const ip = urlObj.hostname;
                const port = urlObj.port;

                document.getElementById('txtAddress').textContent = 'http://' + ip + ':' + port + '/output.txt';
                document.getElementById('m3uAddress').textContent = 'http://' + ip + ':' + port + '/output.m3u';

            } catch (error) {
                console.error('Failed to load addresses:', error);
                const host = window.location.host;
                document.getElementById('txtAddress').textContent = 'http://' + host + '/output.txt';
                document.getElementById('m3uAddress').textContent = 'http://' + host + '/output.m3u';
            }
        }

        async function loadMovies() {
            try {
                const response = await fetch('/get-movies');
                if (!response.ok) {
                    throw new Error('HTTP error! status: ' + response.status);
                }
                allMovies = await response.json();
                if (!Array.isArray(allMovies)) {
                    console.error('Received data is not an array:', allMovies);
                    allMovies = [];
                }
                const container = document.getElementById('moviesContainer');
                
                container.innerHTML = '';
                if (allMovies.length === 0) {
                    container.innerHTML = '<p style="text-align: center; color: #666; font-size: 16px; margin-top: 50px;">🎬 暂无电影数据</p>';
                    return;
                }

                allMovies.forEach(function(movie) {
                    const div = document.createElement('div');
                    div.className = 'movie-item';
                    div.id = 'movie-' + movie.id;
                    
                    let imgHtml = '';
                    const displayImagePath = movie.processedImagePath || movie.imagePath;

                    if (displayImagePath) {
                        if (displayImagePath.startsWith('http')) {
                            imgHtml = '<img src="' + displayImagePath + '" alt="' + movie.name + '">';
                        } else if (displayImagePath.startsWith('/uploads/')) {
                            const fullImagePath = window.location.origin + displayImagePath;
                            imgHtml = '<img src="' + fullImagePath + '" alt="' + movie.name + '">';
                        } else if (displayImagePath.startsWith('./assets/uploads/')) {
                            const relativePath = displayImagePath.substring(2);
                            const fullImagePath = window.location.origin + '/' + relativePath;
                            imgHtml = '<img src="' + fullImagePath + '" alt="' + movie.name + '">';
                        } else {
                            imgHtml = '<div style="width: 60px; height: 60px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); display: flex; align-items: center; justify-content: center; margin-right: 15px; border-radius: 8px; color: white; font-weight: bold;">🎬</div>';
                        }
                    } else {
                        imgHtml = '<div style="width: 60px; height: 60px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); display: flex; align-items: center; justify-content: center; margin-right: 15px; border-radius: 8px; color: white; font-weight: bold;">🎬</div>';
                    }

                    div.innerHTML = 
                        imgHtml +
                        '<div class="movie-info">' +
                            '<div class="movie-name">' + movie.name + '</div>' +
                            '<div class="movie-url">' + movie.url + '</div>' +
                        '</div>' +
                        '<div class="movie-actions">' +
                            '<button class="play-btn" title="PotPlayer" onclick="openPlayer(\'' + movie.url + '\', \'potplayer\')">P</button>' +
                            '<button class="play-btn" title="VLC" onclick="openPlayer(\'' + movie.url + '\', \'vlc\')">V</button>' +
                            '<button class="play-btn" title="MPV" onclick="openPlayer(\'' + movie.url + '\', \'mpv\')">M</button>' +
                            '<button class="edit-btn" onclick="editMovie(' + movie.id + ')">✏️</button>' +
                            '<button class="delete-btn" onclick="deleteMovie(' + movie.id + ')">🗑️</button>' +
                        '</div>';
                    container.appendChild(div);
                });
            } catch (error) {
                console.error('Failed to load movies:', error);
                document.getElementById('moviesContainer').innerHTML = '<p style="text-align: center; color: red; font-size: 16px; margin-top: 50px;">❌ 加载电影列表失败: ' + error.message + '</p>';
                allMovies = [];
            }
        }

        function searchMovies() {
            if (!Array.isArray(allMovies)) {
                console.warn('allMovies is not an array, cannot search.');
                return;
            }
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            const container = document.getElementById('moviesContainer');
            const movieItems = container.getElementsByClassName('movie-item');
            
            let found = false;
            
            for (let i = 0; i < movieItems.length; i++) {
                const movieItem = movieItems[i];
                const movieId = parseInt(movieItem.id.replace('movie-', ''));
                const movie = Array.isArray(allMovies) ? allMovies.find(m => m.id === movieId) : undefined;
                
                if (movie && (movie.name.toLowerCase().includes(searchTerm) || movie.url.toLowerCase().includes(searchTerm))) {
                    movieItem.style.display = '';
                    movieItem.classList.add('highlighted');
                    if (!found) {
                        movieItem.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        found = true;
                    }
                } else {
                    movieItem.classList.remove('highlighted');
                    movieItem.style.display = 'none';
                }
            }
            
            if (!found && searchTerm) {
                container.innerHTML = '<p style="text-align: center; color: #666; font-size: 16px; margin-top: 50px;">❌ 未找到匹配的电影</p>';
            } else if (!searchTerm) {
                for (let i = 0; i < movieItems.length; i++) {
                    movieItems[i].style.display = '';
                    movieItems[i].classList.remove('highlighted');
                }
                loadMovies();
            }
        }

        function openPlayer(url, player) {
            let protocolUrl = '';
            switch(player) {
                case 'potplayer':
                    protocolUrl = 'potplayer://' + url;
                    break;
                case 'vlc':
                    protocolUrl = 'vlc://' + url;
                    break;
                case 'mpv':
                    protocolUrl = 'mpv://' + url;
                    break;
                default:
                    protocolUrl = url;
            }
            window.open(protocolUrl, '_blank');
        }

        function editMovie(id) {
            if (!Array.isArray(allMovies)) {
                console.warn('allMovies is not an array, cannot edit movie.');
                return;
            }
            const movie = allMovies.find(m => m.id == id);
            if (movie) {
                document.getElementById('editId').value = movie.id;
                document.getElementById('name').value = movie.name;
                document.getElementById('url').value = movie.url;
                document.getElementById('imageUrl').value = movie.imagePath || '';
                
                isEditing = true;
                currentMovie = movie;
                document.getElementById('movieForm').classList.add('editing');
                document.getElementById('saveBtn').textContent = '🔄 更新电影';
            }
        }

        async function deleteMovie(id) {
            if (!confirm('⚠️ 确定要删除这个电影吗？')) {
                return;
            }
            
            const response = await fetch('/delete-movie', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'id=' + id
            });
            
            if (response.ok) {
                alert('✅ 删除成功！');
                loadMovies();
            } else {
                alert('❌ 删除失败！');
            }
        }

        function exportData() {
            fetch('/export-data').then(response => {
                if (response.ok) {
                    response.blob().then(blob => {
                        const url = window.URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = 'movie_data.zip';
                        document.body.appendChild(a);
                        a.click();
                        window.URL.revokeObjectURL(url);
                        document.body.removeChild(a);
                    });
                } else {
                    alert('❌ 导出失败！');
                }
            });
        }

        function importData() {
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = '.zip';
            input.onchange = function(event) {
                const file = event.target.files[0];
                if (file) {
                    const formData = new FormData();
                    formData.append('file', file);
                    
                    fetch('/import-data', {
                        method: 'POST',
                        body: formData
                    }).then(response => {
                        if (response.ok) {
                            alert('✅ 导入成功！');
                            loadMovies();
                            loadAddresses();
                        } else {
                            response.text().then(text => {
                                alert('❌ 导入失败: ' + text);
                            });
                        }
                    }).catch(error => {
                        alert('❌ 导入失败: ' + error.message);
                    });
                }
            };
            input.click();
        }

        async function uploadFile() {
            const fileInput = document.getElementById('uploadFile');
            const file = fileInput.files[0];

            if (!file) {
                alert('⚠️ 请选择一个文件！');
                return;
            }

            const formData = new FormData();
            formData.append('file', file);

            try {
                const response = await fetch('/upload-file', {
                    method: 'POST',
                    body: formData
                });

                if (response.ok) {
                    alert('✅ 文件上传成功！');
                    fileInput.value = '';
                } else {
                    const errorText = await response.text();
                    alert('❌ 文件上传失败: ' + errorText);
                }
            } catch (error) {
                console.error('Upload error:', error);
                alert('❌ 文件上传失败: ' + error.message);
            }
        }

        function copyToClipboard(elementId) {
            const element = document.getElementById(elementId);
            const text = element.textContent;
            copyToClipboardText(text);
        }

        function copyToClipboardText(text) {
            if (navigator.clipboard) {
                navigator.clipboard.writeText(text).then(function() {
                    alert('✅ 已复制到剪贴板：' + text);
                }).catch(function(err) {
                    alert('❌ 复制失败: ' + err);
                });
            } else {
                var textArea = document.createElement("textarea");
                textArea.value = text;
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand("copy");
                document.body.removeChild(textArea);
                alert('✅ 已复制到剪贴板：' + text);
            }
        }

        window.onload = function() {
            loadMovies();
            loadAddresses();
            loadIPAddresses();
        };
    </script>
</body>
</html>`))